package com.liliudong.template.biz.service.sys.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liliudong.template.biz.mapper.sys.SysUserRoleMapper;
import com.liliudong.template.biz.service.sys.SysUserRoleService;
import com.liliudong.template.common.entity.sys.SysUserRole;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;

/**
 * sys用户角色服务impl
 *
 * @author ldli5
 * @date 2024/06/20
 */
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements SysUserRoleService {

	@Override
	public void saveBatchWithUserId(Long userId, Collection<Long> roleIds) {
		if (CollUtil.isEmpty(roleIds)) {
			return;
		}
		List<SysUserRole> sysUserRoles = roleIds.stream().map(roleId -> {
			SysUserRole sysUserRole = new SysUserRole();
			sysUserRole.setUserId(userId);
			sysUserRole.setRoleId(roleId);
			return sysUserRole;
		}).toList();
		this.saveBatch(sysUserRoles);
	}

	@Override
	@Transactional
	public void updateBatchWithUserId(Long userId, Collection<Long> roleIds) {
		this.removeByUserId(userId);
		this.saveBatchWithUserId(userId, roleIds);
	}

	@Override
	public void removeByUserId(Long userId) {
		this.remove(
				lambdaQuery().eq(SysUserRole::getUserId, userId).getWrapper()
		);
	}

	@Override
	public List<Long> listIdsByUserId(Long userId) {
		return list(
				lambdaQuery()
						.select(SysUserRole::getRoleId)
						.eq(SysUserRole::getUserId, userId)
						.getWrapper()
		).stream()
				.map(SysUserRole::getRoleId)
				.toList();
	}
}
